<?php

namespace app\modules\indexapi\controllers;

use app\models\LoginForm;
use app\models\User;
use jianyan\easywechat\Wechat;
use yii\rest\Controller;
use yii\web\UnauthorizedHttpException;

class AuthController extends Controller
{
    public function actionLogin()
    {
        $model = new LoginForm();
        if ($model->load(\Yii::$app->request->post(),'') && $model->login()) {
            $user = $model->getUser();
            return [
                'access_token' => $user->access_token,
            ];
        }

        \Yii::$app->response->setStatusCode(401,urlencode(current($model->getFirstErrors())));
        return [];
    }

    public function actionLoginByMp($code)
    {
        /** @var  $wechat Wechat */
        $wechat = \Yii::$app->wechat;
        $miniProgram = $wechat->miniProgram;
        $response = $miniProgram->auth->session($code);
        if (!isset($response['openid']))
            return $response;
        $openid = $response['openid'];
        $user = User::findByMpOpenid($openid);
        \Yii::$app->user->login($user->login());
        return [
            'access_token' => $user->access_token
        ];
    }

    public function actionLogout()
    {
        \Yii::$app->user->logout();
        return [];
    }
}
